'use strict'

import { hashHistory } from 'react-router'
import 'whatwg-fetch'
import fetchJsonp from 'fetch-jsonp'
import { Toast } from 'antd-mobile'
import helper from './helper'

/**
 * 包装`fetch`包括获取`jsonp`
 * 参见 npm package whatwg-fetch fetch-jsonp
 * @param  {[string]}  url     [description]
 * @param  {[object]}  options [description]
 * @param  {Boolean}   jsonp   [description]
 * @return {Promise}
 */
function myFetch(url, options = {}, login = false, isJson = true, jsonp = false) {
  if (login) {
    let authToken = sessionStorage.token
    // let authToken = 'f7e26ebe-b2d3-4461-8fbf-9653be7399bd'
    if (!authToken) {
      Toast.hide()
        // 请先登录
        Toast.fail('请先登录', 2, () => {
          hashHistory.push('/')
        })
    }
    let loginInfo = {
      headers: {
        'x-auth-token': authToken
      }
    }
    options = Object.assign(options, loginInfo)
  }

  if (options && options.headers) {
    options['headers']['Content-Type'] = 'application/json'
  } else {
    options = Object.assign(options, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }

  console.log(options)
  
  const promise = (options !== null) ? fetch(url, options)
    : ((jsonp === true) ? fetchJsonp(url) : fetch(url))

  let res = promise
    .then((response) => {
      // 200 ~ 300正确
      if (response.status == 401) {
        Toast.hide()
        // 请先登录
        Toast.fail('请先登录', 2, () => {
          hashHistory.push('/')
        })
      }

      return response
    })
  if (isJson) {
    return res.then((res) => {
            return res.json()
          })
          .then((json) => {
            if (json === undefined) {
              return {}
            }
            if (json.succeed === undefined && json.error === undefined) {
              return json
            }

            if (!json.succeed || json.error) {
              Toast.hide()
              // 轻提示错误
              Toast.fail(json.message || json.error)
            } else {
              return json
            }
          })
  }
  return res.then((res)=>{
    return {succeed: true}
  })
}

export default myFetch